// 武器基类
class Weapon {
    constructor(type, player) {
        this.type = type;
        this.player = player;
        this.level = 1;
        
        // 从平衡配置中获取基础属性
        const weaponConfig = BALANCE_CONFIG.WEAPONS[type];
        if (weaponConfig) {
            const base = weaponConfig.base;
            this.damage = base.damage;
            this.cooldown = base.cooldown;
            this.lastFireTime = 0;
            this.projectiles = [];
            this.maxProjectiles = base.maxProjectiles;
            this.projectileSpeed = base.projectileSpeed;
            this.projectileLifetime = base.projectileLifetime;
            this.range = base.range;
            this.color = base.color;
            this.destroyOnHit = base.destroyOnHit !== undefined ? base.destroyOnHit : true; // 默认为true
        } else {
            // 如果没有配置，使用默认值
            this.damage = 20;
            this.cooldown = GAME_CONFIG.WEAPON_COOLDOWN;
            this.lastFireTime = 0;
            this.projectiles = [];
            this.maxProjectiles = 5;
            this.projectileSpeed = 5;
            this.projectileLifetime = 2000; // 2秒
            this.range = 200;
            this.destroyOnHit = true;
        }
        
        // 特殊武器属性
        this.orbitalAngle = 0;
        this.orbitalRadius = 50;
        this.cloneOffset = 0;
        
        // 不再调用setupWeapon，因为属性现在从平衡配置中读取
    }
    
    // 升级武器
    upgrade() {
        this.level++;
        
        // 从平衡配置中获取每级增长属性
        const weaponConfig = BALANCE_CONFIG.WEAPONS[this.type];
        if (weaponConfig) {
            const perLevel = weaponConfig.perLevel;
            if (perLevel.damage) this.damage += perLevel.damage;
            if (perLevel.cooldown) this.cooldown += perLevel.cooldown;
            if (perLevel.projectileSpeed) this.projectileSpeed += perLevel.projectileSpeed;
            if (perLevel.range) this.range += perLevel.range;
            if (perLevel.maxProjectiles) this.maxProjectiles += perLevel.maxProjectiles;
            
            // 确保冷却时间不低于50毫秒
            if (this.cooldown < 50) this.cooldown = 50;
        }
    }
    
    // 更新武器
    update(deltaTime, enemies) {
        this.updateProjectiles(deltaTime);
        this.autoFire(deltaTime, enemies);
        
        // 更新特殊武器
        this.updateSpecialWeapons(deltaTime);
    }
    
    // 更新特殊武器
    updateSpecialWeapons(deltaTime) {
        switch(this.type) {
            case WEAPON_TYPES.ORBITAL:
                this.orbitalAngle += 0.1 * deltaTime / 1000; // 修正：将毫秒转换为秒
                break;
            case WEAPON_TYPES.CLONE:
                this.cloneOffset += 0.05 * deltaTime / 1000; // 修正：将毫秒转换为秒
                break;
        }
    }
    
    // 自动开火
    autoFire(deltaTime, enemies) {
        const currentTime = Date.now();
        
        if (currentTime - this.lastFireTime >= this.cooldown) {
            // 环绕弹和护盾不需要敌人就能触发
            if (this.type === WEAPON_TYPES.ORBITAL || this.type === WEAPON_TYPES.SHIELD) {
                this.fire(null);
                this.lastFireTime = currentTime;
            } else {
                // 其他武器需要敌人才能触发
                const nearestEnemy = this.findNearestEnemy(enemies);
                
                if (nearestEnemy && this.getDistanceToEnemy(nearestEnemy) <= this.range) {
                    this.fire(nearestEnemy);
                    this.lastFireTime = currentTime;
                }
            }
        }
    }
    
    // 寻找最近的敌人
    findNearestEnemy(enemies) {
        let nearestEnemy = null;
        let nearestDistance = Infinity;
        
        enemies.forEach(enemy => {
            if (!enemy.isDead) {
                const distance = this.getDistanceToEnemy(enemy);
                if (distance < nearestDistance) {
                    nearestDistance = distance;
                    nearestEnemy = enemy;
                }
            }
        });
        
        return nearestEnemy;
    }
    
    // 获取到敌人的距离
    getDistanceToEnemy(enemy) {
        return Utils.distance(this.player.x, this.player.y, enemy.x, enemy.y);
    }
    
    // 开火
    fire(target) {
        if (this.projectiles.length >= this.maxProjectiles) return;
        
        // 播放武器音效
        if (window.game && window.game.sounds) {
            const weaponType = this.type.toLowerCase();
            if (window.game.sounds[weaponType]) {
                window.game.soundGenerator.playSound(window.game.sounds[weaponType]);
            }
        }
        
        switch(this.type) {
            case WEAPON_TYPES.ORBITAL:
                this.fireOrbital();
                break;
            case WEAPON_TYPES.CLONE:
                if (target) this.fireClone(target);
                break;
            case WEAPON_TYPES.LASER:
                if (target) this.fireLaser(target);
                break;
            case WEAPON_TYPES.SHIELD:
                this.fireShield();
                break;
            default:
                if (target) this.fireNormal(target);
        }
    }
    
    // 普通攻击
    fireNormal(target) {
        const angle = Utils.angle(this.player.x, this.player.y, target.x, target.y);
        const projectile = new Projectile(
            this.player.x,
            this.player.y,
            angle,
            this.projectileSpeed,
            this.damage,
            this.color,
            this.projectileLifetime
        );
        
        // 添加武器类型信息到弹丸
        projectile.weaponType = this.type;
        
        this.projectiles.push(projectile);
    }
    
    // 环绕攻击
    fireOrbital() {
        // 创建环绕弹丸，位置在玩家周围
        const projectile = new Projectile(
            this.player.x + Math.cos(this.orbitalAngle) * this.orbitalRadius,
            this.player.y + Math.sin(this.orbitalAngle) * this.orbitalRadius,
            this.orbitalAngle + Math.PI / 2, // 垂直于半径方向移动
            this.projectileSpeed,
            this.damage,
            this.color,
            this.projectileLifetime
        );
        
        // 标记为环绕弹，特殊处理
        projectile.isOrbital = true;
        projectile.orbitalCenterX = this.player.x;
        projectile.orbitalCenterY = this.player.y;
        projectile.orbitalRadius = this.orbitalRadius;
        projectile.orbitalAngle = this.orbitalAngle;
        projectile.orbitalSpeed = 2.0; // 增加环绕速度，让环绕更明显
        
        this.projectiles.push(projectile);
    }
    
    // 分身攻击
    fireClone(target) {
        // 创建真正的分身实体
        if (window.game && window.game.cloneManager) {
            window.game.cloneManager.addClone();
        }
        
        // 同时发射弹丸
        const angle = Utils.angle(this.player.x, this.player.y, target.x, target.y);
        const offset = Math.sin(this.cloneOffset) * 30;
        
        // 创建多个分身弹丸
        for (let i = 0; i < 3; i++) {
            const cloneAngle = angle + (i - 1) * 0.3;
            const projectile = new Projectile(
                this.player.x + Math.cos(cloneAngle) * offset,
                this.player.y + Math.sin(cloneAngle) * offset,
                cloneAngle,
                this.projectileSpeed,
                this.damage,
                this.color,
                this.projectileLifetime
            );
            
            this.projectiles.push(projectile);
        }
    }
    
    // 激光攻击
    fireLaser(target) {
        const angle = Utils.angle(this.player.x, this.player.y, target.x, target.y);
        
        // 创建激光束而不是弹丸
        const laserBeam = new LaserBeam(
            this.player.x,
            this.player.y,
            angle,
            this.range,
            this.damage,
            this.color,
            this.projectileLifetime * 0.2
        );
        
        // 设置武器引用，这样激光束可以访问玩家位置
        laserBeam.weapon = this;
        
        this.projectiles.push(laserBeam);
    }
    
    // 护盾攻击
    fireShield() {
        // 创建环绕护盾
        for (let i = 0; i < 8; i++) {
            const angle = (i / 8) * Math.PI * 2;
            const projectile = new Projectile(
                this.player.x + Math.cos(angle) * 40,
                this.player.y + Math.sin(angle) * 40,
                angle,
                this.projectileSpeed * 0.5,
                this.damage,
                this.color,
                this.projectileLifetime * 2
            );
            
            this.projectiles.push(projectile);
        }
    }
    
    // 更新弹丸
    updateProjectiles(deltaTime) {
        this.projectiles = this.projectiles.filter(projectile => {
            projectile.update(deltaTime);
            return !projectile.isDead;
        });
    }
    
    // 渲染武器
    render(ctx) {
        this.projectiles.forEach(projectile => projectile.render(ctx));
    }
    
    // 应用武器特殊效果
    applyWeaponEffects(enemy) {
        switch(this.type) {
            case WEAPON_TYPES.FIREBALL:
                // 火球造成持续伤害
                this.applyBurningEffect(enemy);
                break;
            case WEAPON_TYPES.LIGHTNING:
                // 闪电造成连锁伤害
                this.applyChainLightning(enemy);
                break;
            case WEAPON_TYPES.ICE_SHARD:
                // 冰锥造成减速效果
                this.applySlowEffect(enemy);
                break;
            case WEAPON_TYPES.LASER:
                // 激光穿透多个敌人
                this.applyPiercingEffect(enemy);
                break;
        }
    }
    
    // 燃烧效果
    applyBurningEffect(enemy) {
        if (enemy.burningTimer === undefined) {
            enemy.burningTimer = 0;
            enemy.burningDamage = this.burningDamage || 5;
        }
        enemy.burningTimer = 3000; // 3秒燃烧时间
    }
    
    // 连锁闪电
    applyChainLightning(enemy) {
        if (window.game && window.game.enemySpawner) {
            const enemies = window.game.enemySpawner.getEnemies();
            const chainRange = 100;
            let chainCount = 0;
            const maxChainCount = this.chainCount || 3;
            
            enemies.forEach(otherEnemy => {
                if (otherEnemy !== enemy && !otherEnemy.isDead) {
                    const distance = Utils.distance(enemy.x, enemy.y, otherEnemy.x, otherEnemy.y);
                    if (distance <= chainRange && chainCount < maxChainCount) {
                        otherEnemy.takeDamage(this.damage * 0.5);
                        chainCount++;
                    }
                }
            });
        }
    }
    
    // 减速效果
    applySlowEffect(enemy) {
        if (enemy.originalSpeed === undefined) {
            enemy.originalSpeed = enemy.speed;
        }
        const slowEffect = this.slowEffect || 0.5;
        enemy.speed = enemy.originalSpeed * slowEffect; // 减速效果
        enemy.slowTimer = 2000; // 2秒减速时间
    }
    
    // 穿透效果
    applyPiercingEffect(enemy) {
        // 激光穿透，不需要特殊处理，因为激光本身就是穿透的
    }
    
    // 检查弹丸与敌人的碰撞
    checkCollisions(enemies) {
        this.projectiles.forEach(projectile => {
            // 检查是否为激光束
            const isLaserBeam = projectile instanceof LaserBeam;
            
            enemies.forEach(enemy => {
                if (!enemy.isDead && projectile.collidesWith(enemy)) {
                    enemy.takeDamage(this.damage);
                    
                    // 应用武器特殊效果
                    this.applyWeaponEffects(enemy);
                    
                    // 根据武器配置决定是否销毁弹丸
                    if (this.destroyOnHit && !isLaserBeam) {
                        projectile.die();
                    }
                    
                    // 经验值在敌人类的die()方法中给予，避免重复
                }
            });
        });
    }
}

// 弹丸类
class Projectile {
    constructor(x, y, angle, speed, damage, color, lifetime) {
        this.x = x;
        this.y = y;
        this.angle = angle;
        this.speed = speed;
        this.damage = damage;
        this.color = color;
        this.lifetime = lifetime;
        this.maxLifetime = lifetime;
        this.size = GAME_CONFIG.WEAPON_SIZE;
        this.isDead = false;
        
        // 计算速度分量
        this.vx = Math.cos(angle) * speed;
        this.vy = Math.sin(angle) * speed;
    }
    
    // 更新弹丸
    update(deltaTime) {
        // 特殊处理环绕弹
        if (this.isOrbital) {
            // 更新环绕中心点（跟随玩家）
            if (window.game && window.game.player) {
                this.orbitalCenterX = window.game.player.x;
                this.orbitalCenterY = window.game.player.y;
            }
            
            // 环绕弹围绕中心点旋转
            this.orbitalAngle += this.orbitalSpeed * deltaTime / 16.67; // 以60FPS为基准进行调整
            this.x = this.orbitalCenterX + Math.cos(this.orbitalAngle) * this.orbitalRadius;
            this.y = this.orbitalCenterY + Math.sin(this.orbitalAngle) * this.orbitalRadius;
            
            // 更新速度向量（用于尾迹效果）
            this.vx = -Math.sin(this.orbitalAngle) * this.orbitalSpeed * this.orbitalRadius;
            this.vy = Math.cos(this.orbitalAngle) * this.orbitalSpeed * this.orbitalRadius;
        } else {
            // 普通弹丸直线移动
            this.x += this.vx * deltaTime / 16.67; // 以60FPS为基准进行调整
            this.y += this.vy * deltaTime / 16.67; // 以60FPS为基准进行调整
        }
        
        this.lifetime -= deltaTime;
        
        // 检查边界（使用世界边界而不是画布边界）
        // 环绕弹不进行边界检查，因为它们应该跟随玩家
        if (!this.isOrbital) {
            if (this.x < 0 || this.x > GAME_CONFIG.WORLD_WIDTH ||
                this.y < 0 || this.y > GAME_CONFIG.WORLD_HEIGHT) {
                this.die();
            }
        }
        
        // 检查生命周期
        if (this.lifetime <= 0) {
            this.die();
        }
    }
    
    // 渲染弹丸
    render(ctx) {
        ctx.save();

        // 根据剩余生命周期调整透明度
        const alpha = this.lifetime / this.maxLifetime;
        ctx.globalAlpha = alpha;

        // 使用实际的武器图像渲染弹丸
        let spriteName = 'weapon_fireball';
        
        // 优先使用武器类型，如果没有则使用颜色判断
        if (this.weaponType) {
            switch(this.weaponType) {
                case WEAPON_TYPES.KNIFE: spriteName = 'weapon_knife'; break;
                case WEAPON_TYPES.FIREBALL: spriteName = 'weapon_fireball'; break;
                case WEAPON_TYPES.LIGHTNING: spriteName = 'weapon_lightning'; break;
                case WEAPON_TYPES.ICE_SHARD: spriteName = 'weapon_ice'; break;
                case WEAPON_TYPES.LASER: spriteName = 'weapon_laser'; break;
                case WEAPON_TYPES.ORBITAL: spriteName = 'weapon_orbital'; break;
                case WEAPON_TYPES.CLONE: spriteName = 'weapon_orbital'; break;
                case WEAPON_TYPES.SHIELD: spriteName = 'weapon_shield'; break;
            }
        } else {
            // 备用方案：使用颜色判断
            switch(this.color) {
                case '#FFD700': spriteName = 'weapon_knife'; break;
                case '#FF4500': spriteName = 'weapon_fireball'; break;
                case '#00FFFF': spriteName = 'weapon_lightning'; break;
                case '#87CEEB': spriteName = 'weapon_ice'; break;
                case '#FF1493': spriteName = 'weapon_laser'; break;
                case '#32CD32': spriteName = 'weapon_orbital'; break;
                case '#9370DB': spriteName = 'weapon_orbital'; break;
                case '#4169E1': spriteName = 'weapon_shield'; break;
            }
        }

        const weaponSprite = window.spriteManager ? window.spriteManager.getSprite(spriteName) : null;
        if (weaponSprite) {
            // 根据武器类型设置旋转角度，使飞刀等有方向性
            if (spriteName === 'weapon_knife') {
                ctx.save();
                ctx.translate(this.x, this.y);
                // 修正：飞刀图像默认是向右的，需要根据飞行方向调整角度
                // 添加90度偏移，使飞刀图像与飞行方向一致
                ctx.rotate(this.angle + Math.PI / 2);
                // 使用精灵的render方法而不是直接绘制图像
                weaponSprite.render(ctx, 0, 0, this.size * 2, this.size * 2);
                ctx.restore();
            } else if (this.isOrbital && (spriteName === 'weapon_orbital' || spriteName === 'weapon_shield')) {
                // 环绕弹和护盾需要根据环绕角度旋转
                ctx.save();
                ctx.translate(this.x, this.y);
                // 环绕弹应该根据环绕角度旋转，而不是飞行角度
                ctx.rotate(this.orbitalAngle);
                // 使用精灵的render方法而不是直接绘制图像
                weaponSprite.render(ctx, 0, 0, this.size * 2, this.size * 2);
                ctx.restore();
            } else {
                // 使用精灵的render方法而不是直接绘制图像
                weaponSprite.render(ctx, this.x, this.y, this.size * 2, this.size * 2);
            }
        } else {
            // 备用渲染（圆形）
            console.warn(`Sprite not found for ${spriteName}, using fallback rendering`);
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();

            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 1;
            ctx.stroke();
        }

        // 绘制尾迹效果
        this.renderTrail(ctx);

        ctx.restore();
    }
    
    // 渲染尾迹效果
    renderTrail(ctx) {
        const trailLength = 10;
        const trailPoints = [];
        
        for (let i = 1; i <= trailLength; i++) {
            const t = i / trailLength;
            const x = this.x - this.vx * t * 0.1;
            const y = this.y - this.vy * t * 0.1;
            const alpha = (1 - t) * 0.5;
            
            trailPoints.push({ x, y, alpha });
        }
        
        trailPoints.forEach(point => {
            ctx.save();
            ctx.globalAlpha = point.alpha;
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(point.x, point.y, this.size * 0.5, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        });
    }
    
    // 死亡
    die() {
        this.isDead = true;
    }
    
    // 检查与其他对象的碰撞
    collidesWith(other) {
        return Utils.circleCollision(
            this.x, this.y, this.size,
            other.x, other.y, other.size || other.radius || 0
        );
    }
}

class LaserBeam {
    constructor(x, y, angle, length, damage, color, lifetime) {
        this.x = x;
        this.y = y;
        this.angle = angle;
        this.length = length;
        this.damage = damage;
        this.color = color;
        this.lifetime = lifetime;
        this.maxLifetime = lifetime;
        this.width = 3; // 默认宽度为3
        this.isDead = false;
        
        // 计算激光束的末端点
        this.endX = this.x + Math.cos(this.angle) * this.length;
        this.endY = this.y + Math.sin(this.angle) * this.length;
    }
    
    // 更新激光束
    update(deltaTime) {
        this.lifetime -= deltaTime;
        
        // 检查生命周期
        if (this.lifetime <= 0) {
            this.die();
        }
        
        // 更新激光束的起点和终点位置（让激光束随着玩家方向持续发射）
        if (this.weapon && this.weapon.player) {
            const player = this.weapon.player;
            this.x = player.x;
            this.y = player.y;
            this.endX = player.x + Math.cos(this.angle) * this.length;
            this.endY = player.y + Math.sin(this.angle) * this.length;
        }
    }
    
    // 渲染激光束
    render(ctx) {
        ctx.save();
        
        // 根据剩余生命周期调整透明度
        const alpha = this.lifetime / this.maxLifetime;
        ctx.globalAlpha = alpha;
        
        // 激光束应该绘制为从起点到终点的线条
        // 绘制主激光束
        ctx.strokeStyle = this.color;
        ctx.lineWidth = this.width;
        ctx.lineCap = 'round';
        ctx.beginPath();
        ctx.moveTo(this.x, this.y);
        ctx.lineTo(this.endX, this.endY);
        ctx.stroke();
        
        // 绘制高亮效果（更细的白色线条）
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = Math.max(1, this.width / 3);
        ctx.beginPath();
        ctx.moveTo(this.x, this.y);
        ctx.lineTo(this.endX, this.endY);
        ctx.stroke();
        
        // 绘制激光束的发光效果
        ctx.strokeStyle = this.color;
        ctx.lineWidth = this.width * 2;
        ctx.globalAlpha = alpha * 0.3;
        ctx.beginPath();
        ctx.moveTo(this.x, this.y);
        ctx.lineTo(this.endX, this.endY);
        ctx.stroke();
        
        ctx.restore();
    }
    
    // 死亡
    die() {
        this.isDead = true;
    }
    
    // 检查与其他对象的碰撞
    collidesWith(other) {
        return Utils.lineCircleCollision(
            this.x, this.y, this.endX, this.endY,
            other.x, other.y, other.size || other.radius || 0
        );
    }
}

// 武器管理器类
class WeaponManager {
    constructor(player) {
        this.player = player;
        this.weapons = [];
        this.weaponTypes = [
            WEAPON_TYPES.KNIFE,
            WEAPON_TYPES.FIREBALL,
            WEAPON_TYPES.LIGHTNING,
            WEAPON_TYPES.ICE_SHARD,
            WEAPON_TYPES.LASER,
            WEAPON_TYPES.ORBITAL,
            WEAPON_TYPES.CLONE,
            WEAPON_TYPES.SHIELD
        ];
        
        // 初始武器
        this.addWeapon(WEAPON_TYPES.KNIFE);
    }
    
    // 添加武器
    addWeapon(type) {
        const weapon = new Weapon(type, this.player);
        this.weapons.push(weapon);
    }
    
    // 升级武器
    upgradeWeapon(type) {
        const weapon = this.weapons.find(w => w.type === type);
        if (weapon) {
            weapon.upgrade();
        } else {
            this.addWeapon(type);
        }
    }
    
    // 更新所有武器
    update(deltaTime, enemies) {
        this.weapons.forEach(weapon => {
            weapon.update(deltaTime, enemies);
            weapon.checkCollisions(enemies);
        });
    }
    
    // 渲染所有武器
    render(ctx) {
        this.weapons.forEach(weapon => weapon.render(ctx));
    }
    
    // 获取可用升级选项
    getUpgradeOptions() {
        const options = [];
        
        // 为每个武器类型提供升级选项
        this.weaponTypes.forEach(type => {
            const weapon = this.weapons.find(w => w.type === type);
            if (weapon) {
                options.push({
                    type: 'upgrade',
                    weaponType: type,
                    name: this.getWeaponName(type),
                    description: `升级 ${this.getWeaponName(type)} (等级 ${weapon.level})`,
                    effect: `伤害: ${weapon.damage} → ${weapon.damage + 10}`
                });
            } else {
                options.push({
                    type: 'new',
                    weaponType: type,
                    name: this.getWeaponName(type),
                    description: `获得新武器: ${this.getWeaponName(type)}`,
                    effect: '解锁新的攻击方式'
                });
            }
        });
        
        // 添加玩家属性升级选项
        options.push({
            type: 'player_upgrade',
            upgradeType: 'speed',
            name: '速度提升',
            description: '提升移动速度',
            effect: '移动速度 +20%'
        });
        
        options.push({
            type: 'player_upgrade',
            upgradeType: 'health',
            name: '生命强化',
            description: '增加最大生命值',
            effect: '最大生命值 +20'
        });
        
        options.push({
            type: 'player_upgrade',
            upgradeType: 'regen',
            name: '生命恢复',
            description: '持续恢复生命值',
            effect: '每秒恢复1点生命值'
        });
        
        return options;
    }
    
    // 获取武器名称
    getWeaponName(type) {
        switch(type) {
            case WEAPON_TYPES.KNIFE: return '飞刀';
            case WEAPON_TYPES.FIREBALL: return '火球';
            case WEAPON_TYPES.LIGHTNING: return '闪电';
            case WEAPON_TYPES.ICE_SHARD: return '冰锥';
            case WEAPON_TYPES.LASER: return '激光';
            case WEAPON_TYPES.ORBITAL: return '环绕弹';
            case WEAPON_TYPES.CLONE: return '分身';
            case WEAPON_TYPES.SHIELD: return '护盾';
            default: return '未知武器';
        }
    }
    
    // 重置武器管理器
    reset() {
        this.weapons = [];
        this.addWeapon(WEAPON_TYPES.KNIFE);
    }
} 